package logic

import (
	"context"
	"errors"
	"novel-start/models/cache"
	"novel-start/models/mysql"
	"novel-start/pkg"

	"novel-start/novelrpc/internal/svc"
	"novel-start/novelrpc/novelrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type RePasswordLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRePasswordLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RePasswordLogic {
	return &RePasswordLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *RePasswordLogic) RePassword(in *novelrpc.RePasswordRequest) (*novelrpc.RePasswordResponse, error) {
	// todo: add your logic here and delete this line

	var user mysql.User

	if err := user.FindUserById(mysql.DB, in.UserId); err != nil {
		return nil, err
	}

	if err := user.FindUserByMobile(mysql.DB, in.Mobile); err != nil {
		return nil, err
	}

	result, _ := cache.Rdb.Get(l.ctx, "sendSms"+in.Mobile).Result()

	if result == "" {
		return nil, errors.New("验证码还未发送")
	}

	if in.SendSms != result {
		return nil, errors.New("验证码错误,请重新输入")
	}

	if pkg.Md5(in.Password) != pkg.Md5(in.AckPassword) {
		return nil, errors.New("两次密码不一致,请重新输入")
	}

	user.Password = pkg.Md5(in.Password)

	if err := user.UpdatePassword(mysql.DB); err != nil {
		return nil, err
	}

	return &novelrpc.RePasswordResponse{
		UserId: int64(user.ID),
	}, nil
}
